import express, { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { query } from '../database';
import { authenticateToken, requireAdmin } from '../middleware/auth';
import { body, validationResult } from 'express-validator';
import CryptoJS from 'crypto-js';

const router = express.Router();

// 获取所有用户（管理员权限）
router.get('/', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const users = await query(`
      SELECT id, username, role, created_at, updated_at 
      FROM users 
      ORDER BY created_at DESC
    `);

    res.json({
      success: true,
      data: users
    });

  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 获取当前用户信息
router.get('/profile', authenticateToken, async (req: Request, res: Response) => {
  try {
    const userId = (req as any).user.userId;
    
    const users = await query(`
      SELECT id, username, role, created_at, updated_at 
      FROM users 
      WHERE id = ?
    `, [userId]);

    if ((users as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }

    res.json({
      success: true,
      data: (users as any[])[0]
    });

  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 创建用户（管理员权限）
router.post('/', 
  authenticateToken, 
  requireAdmin,
  [
    body('username').isLength({ min: 3 }).withMessage('用户名至少3个字符'),
    body('password').isLength({ min: 6 }).withMessage('密码至少6个字符'),
    body('role').isIn(['admin', 'user']).withMessage('角色只能是admin或user')
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: errors.array()[0].msg
        });
      }

      const { username, password, role } = req.body;

      // 检查用户名是否已存在
      const existingUsers = await query('SELECT id FROM users WHERE username = ?', [username]);
      if ((existingUsers as any[]).length > 0) {
        return res.status(400).json({
          success: false,
          message: '用户名已存在'
        });
      }

      // 创建新用户
      const userId = uuidv4();
      const now = new Date().toISOString();
      const hashedPassword = CryptoJS.MD5(password).toString(); // 前端已经MD5加密，后端再次加密存储
      
      await query(`
        INSERT INTO users (id, username, password, role, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?)
      `, [userId, username, hashedPassword, role, now, now]);

      res.status(201).json({
        success: true,
        message: '用户创建成功'
      });

    } catch (error) {
      console.error('创建用户失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }
);

// 更新用户信息（管理员权限）
router.put('/:id',
  authenticateToken,
  requireAdmin,
  [
    body('username').optional().isLength({ min: 3 }).withMessage('用户名至少3个字符'),
    body('password').optional().isLength({ min: 6 }).withMessage('密码至少6个字符'),
    body('role').optional().isIn(['admin', 'user']).withMessage('角色只能是admin或user')
  ],
  async (req: Request, res: Response) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: errors.array()[0].msg
        });
      }

      const { id } = req.params;
      const { username, password, role } = req.body;
      const currentUserId = (req as any).user.userId;

      // 检查用户是否存在
      const users = await query('SELECT id, username FROM users WHERE id = ?', [id]);
      if ((users as any[]).length === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }

      const currentUser = (users as any[])[0];

      // 如果要更改用户名，检查新用户名是否已被使用
      if (username && username !== currentUser.username) {
        const existingUsers = await query('SELECT id FROM users WHERE username = ? AND id != ?', [username, id]);
        if ((existingUsers as any[]).length > 0) {
          return res.status(400).json({
            success: false,
            message: '用户名已存在'
          });
        }
      }

      // 不能修改自己的角色
      if (role && id === currentUserId) {
        return res.status(400).json({
          success: false,
          message: '不能修改自己的角色'
        });
      }

      // 构建更新字段
      const updateFields = [];
      const updateValues = [];

      if (username) {
        updateFields.push('username = ?');
        updateValues.push(username);
      }

      if (password) {
        updateFields.push('password = ?');
        updateValues.push(CryptoJS.MD5(password).toString()); // 前端已经MD5加密，后端再次加密存储
      }

      if (role) {
        updateFields.push('role = ?');
        updateValues.push(role);
      }

      if (updateFields.length === 0) {
        return res.status(400).json({
          success: false,
          message: '没有需要更新的字段'
        });
      }

      updateFields.push('updated_at = ?');
      updateValues.push(new Date().toISOString());
      updateValues.push(id);

      // 执行更新
      await query(`UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`, updateValues);

      res.json({
        success: true,
        message: '用户信息更新成功'
      });

    } catch (error) {
      console.error('更新用户信息失败:', error);
      res.status(500).json({
        success: false,
        message: '服务器内部错误'
      });
    }
  }
);

// 删除用户（管理员权限）
router.delete('/:id', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const currentUserId = (req as any).user.userId;

    // 不能删除自己
    if (id === currentUserId) {
      return res.status(400).json({ 
        success: false, 
        message: '不能删除自己的账户' 
      });
    }

    // 检查用户是否存在
    const users = await query('SELECT id FROM users WHERE id = ?', [id]);
    if ((users as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }

    // 删除用户
    await query('DELETE FROM users WHERE id = ?', [id]);

    res.json({
      success: true,
      message: '用户删除成功'
    });

  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 更新用户角色（管理员权限）
router.put('/:id/role', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { role } = req.body;
    const currentUserId = (req as any).user.userId;

    if (!['admin', 'user'].includes(role)) {
      return res.status(400).json({ 
        success: false, 
        message: '角色只能是admin或user' 
      });
    }

    // 不能修改自己的角色
    if (id === currentUserId) {
      return res.status(400).json({ 
        success: false, 
        message: '不能修改自己的角色' 
      });
    }

    // 检查用户是否存在
    const users = await query('SELECT id FROM users WHERE id = ?', [id]);
    if ((users as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }

    // 更新用户角色
    await query('UPDATE users SET role = ? WHERE id = ?', [role, id]);

    res.json({
      success: true,
      message: '用户角色更新成功'
    });

  } catch (error) {
    console.error('更新用户角色失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

export default router;
